package com.meow_woof.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.meow_woof.constant.MessageConstant;
import com.meow_woof.constant.StatusConstant;
import com.meow_woof.dto.DishDTO;
import com.meow_woof.dto.DishPageQueryDTO;
import com.meow_woof.entity.Dish;
import com.meow_woof.entity.DishFlavor;
import com.meow_woof.entity.Setmeal;
import com.meow_woof.exception.DeletionNotAllowedException;
import com.meow_woof.mapper.DishFlavorMapper;
import com.meow_woof.mapper.DishMapper;
import com.meow_woof.mapper.SetmealDishMapper;
import com.meow_woof.mapper.SetmealMapper;
import com.meow_woof.result.PageResult;
import com.meow_woof.service.DishService;
import com.meow_woof.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品及对应口味
     * @param dishDTO
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //向菜品表插入一条数据
        dishMapper.insert(dish);
        //获得insert语句生成的主键值
        Long dishId=dish.getId();
        //向口味表插入n条数据
        List<DishFlavor> flavors=dishDTO.getFlavors();
        if (flavors!=null&& flavors.size()>0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);
        }


    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //select * from employee limit 0,10
        //开始分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page=dishMapper.pageQuery(dishPageQueryDTO);
        long total=page.getTotal();
        List<DishVO> records=page.getResult();
        return new PageResult(total,records);

    }

    /**
     * 菜品批量删除
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //判断当前菜品是否能被删除--是否存在起售中的菜品？？
        for(Long id:ids){
            Dish dish =dishMapper.selectById(id);
            if(dish.getStatus()== StatusConstant.ENABLE){
            //当前菜品起售中，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);

            }
        }
        //判断当前菜品是否能够删除--是否被套餐关联？？
        List<Long> setmealIds=setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds !=null&&setmealIds.size()>0){
            //当前菜品被套餐关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
      /*  //删除菜品表中的菜品数据
        for(Long id:ids){
            dishMapper.deleteById(id);
            //删除菜品关联的口味数据
            dishFlavorMapper.deleteByDishId(id);
        }
*/
        //根据菜品id集合批量删除菜品数据
        //sql:delete from dish where id in(?,?,?)
        dishMapper.deleteByIds(ids);
        //根据菜品id集合批量删除关联的口味数据
        //sql:delete from dish_flavor where dish_id in(?,?,?)
        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        log.info("根据id查询菜品:{}",id);
        DishVO dishVO=dishMapper.selectByIdWithFlavour(id);
        List<DishFlavor> flavors=dishFlavorMapper.selectByDishId(id);
        dishVO.setFlavors(flavors);

        return dishVO;
    }

    /**
     * 根据id修改菜品基本信息和对应的口味信息
     * @param dishDTO
     * @return
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish=new Dish();

        BeanUtils.copyProperties(dishDTO,dish);
        //修改菜品表基本信息
        dishMapper.update(dish);
        //删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //重新插入口味数据
        List<DishFlavor> flavors=dishDTO.getFlavors();
        if (flavors!=null&&flavors.size()>0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);
        }

    }
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.selectByCondition(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    public List<Dish> listByCategoryId(Long categoryId) {

        Dish dish =Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        List<Dish> list =dishMapper.selectByCondition(dish);
        return list;
    }
    /**
     * 起售，停售菜品
     * @param status
     * @param id
     * @return
     */
    @Transactional
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish=Dish.builder()
                .id(id)
                .status(status)
                .build();

        dishMapper.update(dish);
        List<Long> ids = new ArrayList<>();
        ids.add(id);
        List<Long> setmealIds =setmealDishMapper.getSetmealIdsByDishIds(ids);
        Long setmealId=setmealIds.get(0);
        Setmeal setmeal=Setmeal.builder()
                .id(setmealId)
                .status(status)
                .build();
        setmealMapper.update(setmeal);

    }
}
